#  RAMP Media Organizer  
#  Database.py
#
#  Copyright (C) 2010  Vishesh Yadav  
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sqlite3 
import os

class Database:
    def __init__(self, dbfile, createIfNotExists=False):
        self.dbfile = dbfile
        self.cursor = None

        if os.path.exists(dbfile): 
            self.conn = sqlite3.connect(dbfile)
        elif createIfNotExists is True:
            self.conn = sqlite3.connect(dbfile)
            self.OpenCursor()
            self.CreateNew()
        else:
            raise IOError("SQLite Database File '%s' doesnt exists"%dbfile)

    def OpenCursor(self):
        self.cursor = self.conn.cursor()

    def CloseSaveCursor(self):
        self.conn.commit()  # Save changes
        self.cursor.close()

    def CreateNew(self):
        tab1 = """CREATE TABLE library(songid INTEGER PRIMARY KEY,
              title TEXT,
              artist TEXT,
              album TEXT,
              genre TEXT,
              year INTEGER,
              length INTEGER,
              path TEXT NOT NULL UNIQUE
            ); """
        self.cursor.execute(tab1)

    def InsertEntry(self, title, artist, album, genre, year, length, path):
        query = """INSERT INTO library
            (title, artist, album, genre, year, length, path) VALUES
            (?, ?, ?, ?, ?, ?, ?)"""
        try:
            self.cursor.execute(query, 
                (title, artist, album, genre, year, length, "%s"%path) )
        except Exception as e:
            print "<Exception> SQLite Insertion: ", e
            print "  path: ", path, '\n'

    def ExecuteSql(self, query):
        return self.cursor.execute(query)

